import pymysql


def saveData(table, my_dict):
    # self.db.set_character_set('utf-8')
    cols = ', '.join(my_dict.keys())
    values = '","'.join(my_dict.values())
    sql = 'insert into %s (%s) values (%s)' % (table, cols, '"' + values + '"')
    print(sql)


my_dict = {
    "first_name": "yutao",
    "last_name": "yubo",
    "age": "18"
}

saveData("pythontest", my_dict)

# 打开数据库连接
db = pymysql.connect("localhost", "root", "root", "pythonmysql")

# 使用cursor()方法创建一个游标对象cursor
cursor = db.cursor()
# 使用execute()方法执行sql查询
# cursor.execute("select version()")
# 使用fetchone()方法获取单条数据
# data = cursor.fetchone()

aa = 2000
mm = 'M'
bb = "yutao"

# sql = "insert into pythontest(first_name,last_name,age,sex,income)" \
#       "values ('%s', '%s', '%d', '%c', '%d')" % \
#       (bb, bb, aa, mm, aa)
# 打印mysql版本
# print("Database version: %s " % data)

sql = "select * from pythontest " \
      "where income > '%d'" % (1000)

try:
    # 执行sql语句
    cursor.execute(sql)
    results = cursor.fetchall()
    for row in results:
        print('进来了')
        fname = row[1]
        lname = row[2]
        age = row[3]
        sex = row[4]
        income = row[5]
        print(type(age))
        # 打印结果 如果数据格式不对，就会造成打印不出来！
        print("fname=%s,lname=%s,age=%d,sex=%s,income=%d" %
              (fname, lname, age, sex, income))
    # 提交到数据库执行
    # db.commit()
except Exception as e:
    # 如果发生错误则回滚
    db.rollback()

# 关闭数据库连接
db.close()
